package fishBids.group3.behaviour.bank;

import es.upm.agents.ontology.Product;
import es.upm.agents.ontology.ToSellProduct;
import es.upm.agents.ontology.ToSellProductResponse;
import fishBids.group3.AgBank;
import fishBids.group3.behaviour.bank.model.Account;
import fishBids.group3.common.Constants;
import fishBids.group3.utils.Utils;
import jade.core.behaviours.SimpleBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.util.leap.Map;
import jade.util.leap.Set;

import java.util.Iterator;

public class BankAuctionOverBehaviour extends SimpleBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = -284773764555908942L;
	
	public BankAuctionOverBehaviour(AgBank bankAg, Map agentsAccounts){
		this.bankAg= bankAg;
		this.agentsAccounts = agentsAccounts;
	}

	@Override
	public void action() {
		//System.out.println("Bank>>> waiting for AuctionOver");
		MessageTemplate mt = MessageTemplate.and( 
			MessageTemplate.MatchProtocol(Constants.AUCTION_OVER),
			MessageTemplate.MatchPerformative(ACLMessage.INFORM)); 
					
		ACLMessage msg = this.bankAg.receive(mt); 
						
		if (msg != null) {
//			System.out.println("Bank>>> receive AuctionOver");
			
			Iterator accounts = this.bankAg.getAgentsAccounts().values().iterator();
			while(accounts.hasNext()){
				Account account = (Account) accounts.next();
				
				  //to sell all the products
				 Iterator keysIterator = account.getItems().keySet().iterator();
				 
				 while(keysIterator.hasNext()){
					 String key = (String) keysIterator.next();
					 Float amount = (Float) account.getItems().get(key);
					 
					 if(amount <= 0 ){
						 continue;
					 }
					 
					 ToSellProduct toSellProduct = new ToSellProduct();
					 
					 Product product = new  Product();
						product.setProductType( 
								key.equalsIgnoreCase(Constants.tuna)     ? Constants.TUNA_TYPE :
								key.equalsIgnoreCase(Constants.salmon)   ? Constants.SALMON_TYPE :
								key.equalsIgnoreCase(Constants.calamari) ? Constants.CALAMARI_TYPE :
								key.equalsIgnoreCase(Constants.prawn)    ? Constants.PRAWN_TYPE : null );
					
						
					 toSellProduct.setProductType(product.getProductType());
					 toSellProduct.setAmount(amount);
					 
						//selling the product to the market
						Utils.sendMessageWithConcept(ACLMessage.REQUEST, this.bankAg.getCodec(), 
								this.bankAg.getOntology(), this.bankAg.getMarketID(),
								Constants.SELL_PRODUCT_NO_PRICE_VARIATION, this.bankAg, toSellProduct);
						
						msg = bankAg.blockingReceive(MessageTemplate.and(
								MessageTemplate.MatchPerformative(ACLMessage.INFORM),
								MessageTemplate.MatchProtocol(Constants.SELL_PRODUCT_NO_PRICE_VARIATION) )); 
						
						ToSellProductResponse toSellProductResponse = (ToSellProductResponse) Utils.extractContent(this.bankAg, msg);
						
						account.setBalance(account.getBalance() + toSellProductResponse.getRevenue() );
						
						if(amount == null){
							amount = new Float(0);
						}
						float newAmount = amount.floatValue() - toSellProduct.getAmount();
						
//						System.out.println("Bank >>>> new amount of product of type " + toSellProduct.getProductType().getType() + ": " + 
//								newAmount);
						
						account.getItems().put(toSellProduct.getProductType().getType(), new Float(newAmount) );
				 }

			}
			
			
			 Set agentsitemsObtainedKey = this.bankAg.getAgentsItemsObtained().keySet();
			 Iterator agentsItemsObtainedKeyIterator = agentsitemsObtainedKey.iterator();
			 
			 while(agentsItemsObtainedKeyIterator.hasNext() ){
				 
				//sellProduct
				
				String agentName = (String) agentsItemsObtainedKeyIterator.next();
//				System.out.println("Bank>>> Final result for agent: " + agentName);
				Account account = (Account) this.bankAg.getAgentsAccounts().get(agentName);
				Map itemsObtained = (Map) this.bankAg.getAgentsItemsObtained().get(agentName);
				Set accountsKeySet = itemsObtained.keySet();
				
				  Iterator accountKey = accountsKeySet.iterator();
				  
				  while( accountKey.hasNext() ){
					  
					  String key = (String) accountKey.next();
				  }
				 
			  
				 System.out.println(agentName + "- T: " + itemsObtained.get(Constants.TUNA_TYPE.getType()) + " kg.; S: " + 
						 itemsObtained.get(Constants.SALMON_TYPE.getType()) + " kg.; C: " + 
						 itemsObtained.get(Constants.CALAMARI_TYPE.getType()) + " kg.; P: " + 
						 itemsObtained.get(Constants.PRAWN_TYPE.getType()) + " kg. - YIELD: " + account.getBalance() + " euros");
			 }
			 end = true;
		}
		block();
			
	}
		
	
	public boolean done()
	{
		return end;
	}
	
	AgBank bankAg;
	Map agentsAccounts;
	boolean end;
}
